package com.whisperly.echotalk.other;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.LocaleList;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.whisperly.echotalk.bllmodel.UserQuery;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.DatabaseHelper;
import com.whisperly.echotalk.starryb.utils.GlobalData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SQLQueryListener;

public class Records extends AppCompatActivity {
    private ListView dateListView;
    private ArrayAdapter<String> dateAdapter;

    private Button btn_back;
    private String userId;
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.records);

        AppsManager.addActivity(this);

        dateListView = findViewById(R.id.date_list_view);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(v -> Records.super.onBackPressed());
        userId = getCurrentUserId();

        Log.e("userId",userId);

        loadDates();
    }

    private void loadDates() {
        Set<String> uniqueDates = new HashSet<>();
        BmobQuery<UserQuery> userQueryBmobQuery = new BmobQuery<>();
        userQueryBmobQuery.doSQLQuery("select * from UserQuery where userId = '" + userId + "'", new SQLQueryListener<UserQuery>() {
            @Override
            public void done(BmobQueryResult<UserQuery> bmobQueryResult, BmobException e) {
                if (e == null){
                    List<UserQuery> results = bmobQueryResult.getResults();
                    Log.e("userId",results.toString());
                    for (UserQuery result : results) {
                        Log.e("userId",result.getDate());
                        uniqueDates.add(result.getDate());
                    }
                    List<String> dates = new ArrayList<>(uniqueDates); // 将Set转换为List
                    Collections.sort(dates);

                    dateAdapter = new ArrayAdapter<>(Records.this, android.R.layout.simple_list_item_1, dates);
                    dateListView.setAdapter(dateAdapter);
                    dateListView.setOnItemClickListener((parent, view, position, id) -> {
                        String selectedDate = dates.get(position);
                        showQueriesForDate(selectedDate);
                    });
                }
            }
        });
    }

    private void showQueriesForDate(String date) {
        List<String> queriesDates = new ArrayList<>();;
        Log.e("data",date);
        BmobQuery<UserQuery> userQueryBmobQuery = new BmobQuery<>();
        userQueryBmobQuery.doSQLQuery("select * from UserQuery where date = '" + date + "' and  userId = '"+userId+"'", new SQLQueryListener<UserQuery>() {
            @Override
            public void done(BmobQueryResult<UserQuery> bmobQueryResult, BmobException e) {
                if (e == null){
                    List<UserQuery> results = bmobQueryResult.getResults();
                    Log.e("results",results.toString());
                    for (UserQuery result : results) {
                        queriesDates.add(result.getQueries());
                    }
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(Records.this);
                Log.e("date11111111",queriesDates.toString());
                builder.setTitle(getString(R.string.Questions_on) + ":" + date)
                        .setItems(queriesDates.toArray(new String[0]), null)
                        .setPositiveButton(R.string.OK, null).setCancelable(false)
                        .show();
            }
        });
    }

    private String getCurrentUserId() {
        return GlobalData.getUser().getObjectId();
    }
}
